package com.scau.service.impl;

import com.scau.dao.GoodsMapper;

import com.scau.dao.cache.RedisDao;
import com.scau.dto.ConstantClass;
import com.scau.exception.FileUtilException;
import com.scau.exception.GoodsStockException;
import com.scau.handleException.ResultCode;
import com.scau.pojo.Goods;
import com.scau.pojo.GoodsExample;
//import com.scau.pojo.integration.GoodsInegration;
import com.scau.service.IGoodsService;

import com.scau.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.midi.Soundbank;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;



@Service
public class GoodsServiceImpl implements IGoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    private RedisDao redisDao;


    @Value("${server.address}")
    private String serverAddress;
    @Value("${store.goods.dir}")
    private String storeDir;
    @Value("${store.goods.mapping}")
    private String storeMapping;

    //获得某品牌商所有商品
    @Override
    public List<Goods> getAllGoodss(){
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdIsNotNull();
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return goodsList;
    }
    @Override
    public List<Goods> getBrandGoodss(String username) {
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andUsernameEqualTo(username);

        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return goodsList;
    }

    //按照商品名字模糊搜索
    @Override
    public List<Goods> getBrandGoodsByName(String username, String goodsName){
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andGoodsNameLike(goodsName).andUsernameEqualTo(username);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        return goodsList;
    }

    //获得某个商品
    @Override
    public Goods getBrandGoods(String id){
        Goods goods = redisDao.getGoods(id);
        if(goods != null) return goods;
        else {
            goods = goodsMapper.selectByPrimaryKey(id);
            if(goods != null){
                redisDao.putGoods(goods);
            }
        }
        return goods;
    }


//品牌商添加商品
    @Override
    public int addBrandGoods(Goods goods, MultipartFile img) throws FileUtilException {

        //还未添加事务管理
        int rows = 0;

        //生成唯一标识
        String id = UUID.randomUUID().toString().replace("-","");
        //生成图片文件路径
        String absoluteDir = generateDir(ConstantClass.ABSOLUTE_PATH,goods);
        String mappingDir = generateDir(ConstantClass.MAPPING_PATH,goods);
        String fileName = generateFileName(img,id);
        FileUtil.createDir(absoluteDir);

        System.out.println("absoluteDir:" + absoluteDir );
        System.out.println("MappingDir:" + mappingDir );

        //增加商品信息:设置商品id，设置商品初始状态
        goods.setId(id);
        goods.setStatus(ConstantClass.GOODS_INITIAL_STATUS);
        //存入数据库的是映射路径
        goods.setImgUrl(serverAddress+mappingDir+fileName);

//        System.out.println(goods.toString());

        //保存商品信息至数据库
        rows = goodsMapper.insert(goods);
        //存入redis
        redisDao.putGoods(goods);
        //保存图片到磁盘
        FileUtil.saveFile(img,absoluteDir+fileName);

        return rows;
    }

    //品牌商更新商品
    @Override
    public Goods updateBrandGoods(Goods goods, MultipartFile img) {

        //还未添加事务管理
        int rows = 0;
        //获取图片映射路径
        String imgUrl = goods.getImgUrl();
        //转成绝对路径
        String path = analyzeImgUrl(imgUrl);
        System.out.println("path:" + path);

        try {
            if(img != null){//不为空时才修改图片
                //先删除原有图片
                FileUtil.deleteFile(path);
                //更新的文件后缀可能与原有文件名不同
                goods.setImgUrl(imgUrl.substring(0,imgUrl.lastIndexOf(".")) + img.getOriginalFilename().substring(img.getOriginalFilename().lastIndexOf(".")));
                String absolutePath = analyzeImgUrl(goods.getImgUrl());
                FileUtil.saveFile(img,absolutePath);
            }
            rows = goodsMapper.updateByPrimaryKey(goods);
            //存入redis
            redisDao.putGoods(goods);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("修改失败");
        }finally {
            System.out.println("修改成功");
        }
        return goods;
    }

    //更新商品状态
    @Override
    public int updateBrandGoodsStatus(Goods goods) {

        //返回受影响的行数
        int rows = goodsMapper.updateByPrimaryKeySelective(goods);
        redisDao.updateGoodsBySelected(goods);
        return rows;
    }
    //更新商品库存:借买方下订单/取消订单
    public void updateBrandGoodsStock(String id, int quantity,int type) throws GoodsStockException {
        Goods goods = goodsMapper.selectByPrimaryKey(id);

        if(type == ConstantClass.REDUCE_GOODS ){
            //借买方下订单，减少商品库存
            if(goods.getStock()<quantity){
                //销量不足，无法销售
                //抛出异常
                throw new GoodsStockException();
            }else{
                goods.setStock(goods.getStock()-quantity);
            }
        }else if(type == ConstantClass.INCREASE_GOODS){
            //取消订单，增加商品库存
            goods.setStock(goods.getStock()+quantity);
        }
        goodsMapper.updateByPrimaryKey(goods);
        redisDao.putGoods(goods);

    }

    @Override
    public Goods deleteBrandGoods(String id) throws FileUtilException {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        //删除数据库记录
        goodsMapper.deleteByPrimaryKey(goods.getId());
        redisDao.deleteGoods(goods.getId());
        //删除文件
        System.out.println(goods.getImgUrl());
        FileUtil.deleteFile(analyzeImgUrl(goods.getImgUrl()));
        System.out.println("删除成功");
        return goods;
    }

    private String generateFileName(MultipartFile img,String id){
        //重命名图片
        String fileName = id + img.getOriginalFilename().substring(img.getOriginalFilename().lastIndexOf("."));
        return fileName;
    }
    private String generateDir(int type, Goods goods){
        String dir = "";
        if(type == ConstantClass.ABSOLUTE_PATH){
            //生成图片文件存储的真实绝对路径
            dir = storeDir + goods.getUsername()+"/"+goods.getBrandId()+"/";
        }else if(type == ConstantClass.MAPPING_PATH){
            //生成访问图片文件的映射路径
            dir = storeMapping + goods.getUsername()+"/"+goods.getBrandId()+"/";
        }else {
            //传入的参数不正确，抛出异常
        }
        return dir;
    }
    //解析数据库存储的图片映射路径
    private String analyzeImgUrl(String mappingDir){
        return storeDir + mappingDir.substring(mappingDir.lastIndexOf("/GoodsPic")+ConstantClass.CUT_PATH);

    }

}
